package org.starapp.rbac.action;

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.starapp.rbac.entity.Users;
import org.starapp.rbac.exception.ValidateCodeInvalidException;
import org.starapp.rbac.parameters.AppParameter;
import org.starapp.rbac.utils.ValidateCode;

/**
 * 功能： 签入帐户 签出帐户 生成验证码
 * 
 * @author 王强
 * 
 */
@Controller
public class LoginController {

	@RequestMapping(value = "/login", method = RequestMethod.GET)
	public String loginPage() {
		return "account/login";
	}

	@RequestMapping(value = "/login", method = RequestMethod.POST, produces = { "application/json;charset=UTF-8" })
	public String login(Users currUser, HttpSession session,
			HttpServletRequest request, Model model) {
		if (AppParameter.NEED_VALIDATECODE) {
			String code = (String) session.getAttribute("validateCode");
			String submitCode = WebUtils.getCleanParam(request, "validateCode");
			if (StringUtils.isEmpty(submitCode)
					|| !StringUtils.equals(code, submitCode.toLowerCase())) {
				model.addAttribute("userId", currUser.getUserId());
				request
						.setAttribute(
								FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME,
								"validateCodeError");
				return "account/login";
			}
		}
		String rememberMe = WebUtils.getCleanParam(request, "rememberMe");
		Subject user = SecurityUtils.getSubject();
		UsernamePasswordToken token = new UsernamePasswordToken(currUser
				.getUserId(), currUser.getPassword());
		if (!StringUtils.isEmpty(rememberMe) && rememberMe.equals("on")) {
			token.setRememberMe(true);
		}
		try {
			user.login(token);
			return "redirect:/";
		} catch (AuthenticationException e) {
			token.clear();
			model.addAttribute("userId", currUser.getUserId());
			String msg = "";
			Object obj = request
					.getAttribute(org.apache.shiro.web.filter.authc.FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME);
			if (obj instanceof Exception) {
				AuthenticationException authException = (AuthenticationException) obj;
				if (authException instanceof ValidateCodeInvalidException) {
					msg = "验证码错误";
				}
			}
			if (e instanceof UnknownAccountException) {
				msg = e.getMessage();
			}
			if (e instanceof AccountException) {
				msg = e.getMessage();
			}
			request.setAttribute(
					FormAuthenticationFilter.DEFAULT_ERROR_KEY_ATTRIBUTE_NAME,
					msg);
			return "account/login";
		}
	}

	@RequestMapping(value = "/logout")
	@ResponseBody
	public void logout(HttpServletRequest request) {
		Subject subject = SecurityUtils.getSubject();
		if (subject != null) {
			subject.logout();
		}
		request.getSession().invalidate();
	}

	/**
	 * 生成验证码
	 * 
	 * @param request
	 * @param response
	 * @throws IOException
	 */
	@RequestMapping(value = "/validateCode")
	public void validateCode(HttpServletRequest request,
			HttpServletResponse response) throws IOException {
		response.setHeader("Cache-Control", "no-cache");
		String verifyCode = ValidateCode.generateTextCode(
				ValidateCode.TYPE_NUM_ONLY, 4, null);
		request.getSession().setAttribute("validateCode", verifyCode);
		response.setContentType("image/jpeg");
		BufferedImage bim = ValidateCode.generateImageCode(verifyCode, 90, 30,
				3, true, Color.WHITE, Color.BLACK, null);
		ImageIO.write(bim, "JPEG", response.getOutputStream());
	}
}